// DOM元素
const passwordOutputEl = document.getElementById('password-output');
const lengthSliderEl = document.getElementById('length-slider');
const lengthValueEl = document.getElementById('length-value');
const uppercaseEl = document.getElementById('uppercase');
const lowercaseEl = document.getElementById('lowercase');
const numbersEl = document.getElementById('numbers');
const symbolsEl = document.getElementById('symbols');
const generateBtnEl = document.getElementById('generate-btn');
const copyBtnEl = document.getElementById('copy-btn');
const strengthTextEl = document.getElementById('strength-text');
const strengthBarsEl = document.querySelector('.strength-bars');
const crackTimeEl = document.getElementById('crack-time');
const diversityEl = document.getElementById('diversity');
const toastNotificationEl = document.getElementById('toast-notification');

// 字符集定义
const charSets = {
    uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
    lowercase: 'abcdefghijklmnopqrstuvwxyz',
    numbers: '0123456789',
    symbols: '!@#$%^&*()_+~`|}{[]:;?><,./-='
};

// 初始化函数
function initPasswordGenerator() {
    // 初始生成密码
    generatePassword();
    
    // 添加事件监听器
    lengthSliderEl.addEventListener('input', updateLengthValue);
    generateBtnEl.addEventListener('click', generatePassword);
    copyBtnEl.addEventListener('click', copyToClipboard);
    uppercaseEl.addEventListener('change', ensureAtLeastOneOption);
    lowercaseEl.addEventListener('change', ensureAtLeastOneOption);
    numbersEl.addEventListener('change', ensureAtLeastOneOption);
    symbolsEl.addEventListener('change', ensureAtLeastOneOption);
    
    // 添加键盘快捷键支持
    document.addEventListener('keydown', handleKeyboardShortcuts);
}

// 更新长度显示
function updateLengthValue() {
    lengthValueEl.textContent = lengthSliderEl.value;
}

// 确保至少选择了一个字符集选项
function ensureAtLeastOneOption() {
    const hasSelectedOption = uppercaseEl.checked || 
                            lowercaseEl.checked || 
                            numbersEl.checked || 
                            symbolsEl.checked;
    
    if (!hasSelectedOption) {
        // 确保至少有一个选项被选中，这里默认选中小写字母
        lowercaseEl.checked = true;
    }
}

// 生成随机密码
function generatePassword() {
    // 获取密码长度和选中的字符集
    const length = parseInt(lengthSliderEl.value);
    let availableChars = '';
    let password = '';
    
    // 构建可用字符集
    if (uppercaseEl.checked) availableChars += charSets.uppercase;
    if (lowercaseEl.checked) availableChars += charSets.lowercase;
    if (numbersEl.checked) availableChars += charSets.numbers;
    if (symbolsEl.checked) availableChars += charSets.symbols;
    
    // 如果没有选中任何字符集，显示错误信息
    if (availableChars.length === 0) {
        passwordOutputEl.value = '请至少选择一种字符类型';
        updateStrengthIndicator('');
        updateStats('', '');
        return;
    }
    
    // 确保至少包含每个选中类型的一个字符
    const requiredChars = [];
    if (uppercaseEl.checked) {
        requiredChars.push(getRandomChar(charSets.uppercase));
    }
    if (lowercaseEl.checked) {
        requiredChars.push(getRandomChar(charSets.lowercase));
    }
    if (numbersEl.checked) {
        requiredChars.push(getRandomChar(charSets.numbers));
    }
    if (symbolsEl.checked) {
        requiredChars.push(getRandomChar(charSets.symbols));
    }
    
    // 生成剩余的随机字符
    for (let i = requiredChars.length; i < length; i++) {
        password += getRandomChar(availableChars);
    }
    
    // 合并必要字符和随机字符
    password = requiredChars.join('') + password;
    
    // 打乱密码字符顺序（Fisher-Yates 洗牌算法）
    password = shuffleString(password);
    
    // 更新密码显示
    passwordOutputEl.value = password;
    
    // 更新密码强度指示器
    updateStrengthIndicator(password);
    
    // 更新统计信息
    updateStats(password);
}

// 从字符集中获取随机字符
function getRandomChar(charSet) {
    return charSet.charAt(Math.floor(Math.random() * charSet.length));
}

// 打乱字符串顺序（Fisher-Yates 洗牌算法）
function shuffleString(str) {
    const array = str.split('');
    
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]]; // 交换元素
    }
    
    return array.join('');
}

// 更新密码强度指示器
function updateStrengthIndicator(password) {
    if (!password || password === '请至少选择一种字符类型') {
        strengthTextEl.textContent = '密码强度: 未生成';
        strengthBarsEl.className = 'strength-bars';
        return;
    }
    
    // 计算密码强度分数（0-4）
    let strengthScore = 0;
    const length = password.length;
    
    // 长度得分
    if (length >= 16) strengthScore += 2;
    else if (length >= 10) strengthScore += 1;
    
    // 字符多样性得分
    if (/[A-Z]/.test(password)) strengthScore += 1;
    if (/[a-z]/.test(password)) strengthScore += 1;
    if (/[0-9]/.test(password)) strengthScore += 1;
    if (/[^A-Za-z0-9]/.test(password)) strengthScore += 1;
    
    // 归一化得分到 0-4
    strengthScore = Math.min(4, Math.floor(strengthScore / 2));
    
    // 更新强度文本和样式
    let strengthText, strengthClass;
    
    switch (strengthScore) {
        case 0:
            strengthText = '密码强度: 极弱';
            strengthClass = 'strength-weak';
            break;
        case 1:
            strengthText = '密码强度: 弱';
            strengthClass = 'strength-weak';
            break;
        case 2:
            strengthText = '密码强度: 一般';
            strengthClass = 'strength-fair';
            break;
        case 3:
            strengthText = '密码强度: 强';
            strengthClass = 'strength-good';
            break;
        case 4:
            strengthText = '密码强度: 极强';
            strengthClass = 'strength-strong';
            break;
    }
    
    strengthTextEl.textContent = strengthText;
    strengthBarsEl.className = 'strength-bars ' + strengthClass;
}

// 更新统计信息
function updateStats(password) {
    if (!password || password === '请至少选择一种字符类型') {
        crackTimeEl.textContent = '未生成';
        diversityEl.textContent = '未生成';
        return;
    }
    
    // 计算密码空间大小
    let charsetSize = 0;
    if (uppercaseEl.checked) charsetSize += 26;
    if (lowercaseEl.checked) charsetSize += 26;
    if (numbersEl.checked) charsetSize += 10;
    if (symbolsEl.checked) charsetSize += 32; // 估计特殊符号数量
    
    const length = password.length;
    const combinations = Math.pow(charsetSize, length);
    
    // 计算估计破解时间（假设每秒尝试10亿次）
    const attemptsPerSecond = 1e9;
    const secondsToCrack = combinations / attemptsPerSecond;
    const crackTime = formatTime(secondsToCrack);
    
    // 计算字符多样性百分比
    let uniqueChars = new Set(password);
    let diversityPercentage = Math.round((uniqueChars.size / length) * 100);
    
    crackTimeEl.textContent = crackTime;
    diversityEl.textContent = `${diversityPercentage}%`;
}

// 格式化时间
function formatTime(seconds) {
    if (seconds < 1) return '< 1秒';
    
    const minutes = seconds / 60;
    if (minutes < 1) return `${Math.round(seconds)}秒`;
    
    const hours = minutes / 60;
    if (hours < 1) return `${Math.round(minutes)}分钟`;
    
    const days = hours / 24;
    if (days < 1) return `${Math.round(hours)}小时`;
    
    const years = days / 365;
    if (years < 1) return `${Math.round(days)}天`;
    
    const decades = years / 10;
    if (decades < 1) return `${Math.round(years)}年`;
    
    const centuries = decades / 10;
    if (centuries < 1) return `${Math.round(decades)}十年`;
    
    const millenniums = centuries / 10;
    if (millenniums < 1) return `${Math.round(centuries)}世纪`;
    
    return `> ${Math.round(millenniums)}千年`;
}

// 复制到剪贴板
function copyToClipboard() {
    const password = passwordOutputEl.value;
    
    if (!password || password === '请至少选择一种字符类型') {
        showToast('没有可复制的密码');
        return;
    }
    
    // 使用现代剪贴板API
    if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(password)
            .then(() => {
                showToast('✅ 已复制到剪贴板');
            })
            .catch(err => {
                fallbackCopyToClipboard(password);
            });
    } else {
        fallbackCopyToClipboard(password);
    }
}

// 备用复制方法
function fallbackCopyToClipboard(text) {
    passwordOutputEl.select();
    passwordOutputEl.setSelectionRange(0, 99999); // 兼容移动设备
    
    try {
        document.execCommand('copy');
        showToast('✅ 已复制到剪贴板');
    } catch (err) {
        showToast('❌ 复制失败，请手动复制');
    }
    
    // 清除选择
    window.getSelection().removeAllRanges();
}

// 显示提示框
function showToast(message) {
    toastNotificationEl.textContent = message;
    toastNotificationEl.classList.add('show');
    
    // 3秒后隐藏提示框
    setTimeout(() => {
        toastNotificationEl.classList.remove('show');
    }, 3000);
}

// 处理键盘快捷键
function handleKeyboardShortcuts(e) {
    // Ctrl/Cmd + G: 生成密码
    if ((e.ctrlKey || e.metaKey) && e.key === 'g') {
        e.preventDefault();
        generatePassword();
    }
    
    // Ctrl/Cmd + C: 复制密码（当密码框有焦点时）
    if ((e.ctrlKey || e.metaKey) && e.key === 'c' && document.activeElement === passwordOutputEl) {
        e.preventDefault();
        copyToClipboard();
    }
}

// 页面加载时初始化
window.addEventListener('DOMContentLoaded', initPasswordGenerator);